package com.lintf.starter.sdk;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;

// FileUploader.java
public class FileUploader {

    private final String endpoint;

    private final String accessKey;

    // 基础构造函数
    public FileUploader(String endpoint, String accessKey) {
        this.endpoint = endpoint;
        this.accessKey = accessKey;
    }

    // 文件上传方法
    public String upload(File file) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost post = new HttpPost(endpoint + "/upload");

            // 构建multipart请求
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", file);
            builder.addTextBody("accessKey", accessKey);

            post.setEntity(builder.build());

            // 发送请求
            try (CloseableHttpResponse response = httpClient.execute(post)) {
                if (response.getStatusLine().getStatusCode() == 200) {
                    return EntityUtils.toString(response.getEntity());
                } else {
                    throw new IOException("Upload failed: " +
                            response.getStatusLine().getStatusCode());
                }
            }
        }
    }
}